﻿using Blazored.LocalStorage;
using BootstrapBlazor.Components;
using BootstrapBlazorApp.Shared.Data.SYS;
using BootstrapBlazorApp.Shared.Pages.Account;
using BootstrapBlazorApp.Shared.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Security.Principal;
using System.Web;

namespace BootstrapBlazorApp.Shared.Shared
{
    /// <summary>
    /// 
    /// </summary>
    public sealed partial class MainLayout
    {
        private bool UseTabSet { get; set; } = false;

        private string Theme { get; set; } = "";

        private bool IsOpen { get; set; }

        private bool IsFixedHeader { get; set; } = true;

        private bool IsFixedFooter { get; set; } = false;

        private bool IsFullSide { get; set; } = false;


        private List<MenuItem>? Menus { get; set; }


        public CurrentUser currentUser { get; set; } = new CurrentUser();

        /// <summary>
        /// 当前Token信息
        /// </summary>
        [CascadingParameter]
        private ITokenContext? Context { get; set; }

        /// <summary>

        /// 强制刷新标志

        /// </summary>

        private bool forceRender { get; set; } = false;

        private void LogoutEvent(object username)
        {
            //msg.Info($"See you later {(string)username}");
            //通过 LoginControl 组件回调 接收强制刷新消息
            forceRender = true;
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {

            base.OnAfterRender(firstRender);



            if (firstRender || forceRender)
            {
                forceRender = false;
                if (!Context.IsAuthenticated)
                    nav.NavigateTo("/Account/Login");
                else
                {
                    if (await local.ContainKeyAsync(ClientAppKey.CurrentUser))
                    {
                        currentUser = await local.GetItemAsync<CurrentUser>(ClientAppKey.CurrentUser);
                        if (currentUser.Avatar == null)
                        {
                            currentUser.Avatar = "_content/BootstrapBlazorApp.Shared/images/Argo.png";
                        }
                    }

                    StateHasChanged();
                }

            }

        }

        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override void OnInitialized()
        {

            base.OnInitialized();
            //判断是否企业微信调用
            var uri = nav.ToAbsoluteUri(nav.Uri);
            // 获取code
            var code = HttpUtility.ParseQueryString(uri.Query).Get("code");

            var appid = HttpUtility.ParseQueryString(uri.Query).Get("appcode");
            if (code != null)
            {
                
                if (Context.IsAuthenticated)
                {
                    //已授权 如果appid不一致 更新appid
                    currentUser =  local.GetItemAsync<CurrentUser>(ClientAppKey.CurrentUser).Result;
                    if(appid != currentUser.AppCode)
                    {
                        currentUser.AppCode = appid;
                        local.SetItemAsync(ClientAppKey.CurrentUser, currentUser);
                        Context.SetSession(ClientAppKey.CurrentUser, currentUser);
                    }
                }
                else
                {
                    var model =  Request.System.ThreeLoginAsync(new LoginModel
                    {
                        Account = code,
                        Password = appid
                    }).Result;
                    if (model.succeeded)
                    {
                        var user = new CurrentUser()
                        {
                            Account = model.data.Account,
                            UserName = model.data.UserName,
                            AppCode = model.data.AppCode,
                            Avatar = model.data.Avatar,
                        };
                        local.SetItemAsync(ClientAppKey.CurrentUser, user);
                        //设置Session
                        Context.SetSession(ClientAppKey.CurrentUser, user);
                    }
                    else
                    {
                         msg.Show(new MessageOption()
                        {
                            Color = Color.Danger,
                            Content = model.errors
                        });
                    }
                }
            }
            if (Context.IsAuthenticated)
            {
                var menus = Request.System.QueryMenusByAccountAsync(Context.CurrentUser.Account, Context.CurrentUser.AppCode).Result;
                Menus = menus.data;

                var buttons = Request.System.QueryButtonsByAccountAsync(Context.CurrentUser.Account).Result.data; 
                Context.SetSession(ClientAppKey.UserPermissions, buttons);
            }
           
        }

        private List<MenuItem> GetIconSideMenuItems(IEnumerable<MenuDto> items, string? ParentCode)
        {
            var ret = new List<MenuItem>();
            ret.AddRange(items.Where(i => i.ParentCode == ParentCode).Select((menu, index) => new MenuItem
            {
                Text = menu.Name,
                Icon = $"fa-solid fa-fw {menu.Icon}",
                Url = menu.Url,
                Match =  NavLinkMatch.All,
                // 获得子项集合
                Items = GetIconSideMenuItems(items.Where(i => i.ParentCode == menu.MenuCode), menu.MenuCode)
            }));
            return ret;
        }
    }
}
